import React, { Component } from 'react'
import PropTypes from 'prop-types'
import {Button} from 'antd';

// 受控的值是直接从props中取的， 如果子组件想更新这个值必须通过回调函数属性通过更新外层组件状态来改变传入的props,最终改变显示的值
// 不受控的值是从自身的state中取的， 一般可以接收一个初始值，仅在组件构造时接收

class Counter extends Component<any,any>{

    constructor(props:any) {
        super(props);
        const {defaultCount} = props;
        this.state = {
            count:defaultCount??0,
        }
    }
    handleClick=()=>{
        const {count} = this.state;
        this.setState({
            count: count+1,
        })
        this.props.onAdd?.();
    }
    render(){
        const {count} = this.state; // 如果只在构造时，从props.defaultCount取值，defaultCount属性不受控
        const {defaultCount} = this.props; // 如果直接从props取值， defaultCount 属性受控
        return (
            <div>
                <div>{defaultCount}</div>
                <Button onClick={this.handleClick}>我是子组件，点击我加一</Button>
            </div>
        )
    }
}

export default class index extends Component<any,any> {
    static propTypes = {
        prop: PropTypes
    }
    state={
        defaultCount: 1000,
    }
    handleClick = ()=>{
        const {defaultCount} = this.state;
        this.setState({
            defaultCount : defaultCount+1,
        })
    }
    render() {
        const {defaultCount} = this.state;
        return (
            <div style={{padding:20}}>
                <div>
                    <Counter onAdd={this.handleClick} defaultCount={defaultCount} />
                </div>
                <hr/>
                <div>defaultCount:{defaultCount}</div>
                <div>
                <Button onClick={this.handleClick}>我是父组件，点击我加一</Button>
                </div>
            </div>
        )
    }
}
